import React, { useEffect, useState} from 'react';
import {Layout, Row, Col, Card, Button, Modal, theme, CardProps, message} from 'antd';
import type { RadioChangeEvent } from 'antd';
import { Link, history } from '@umijs/max';
const { Content } = Layout;


import {buyPointsUsingPost, getLoginUserUsingGet, isPayUsingPost} from "@/services/openAPI-backend/userController";
import {keyframes} from "antd-style";



const Vip = () => {
  const [loginUser, setLoginUser] = useState<any>();
  const [value, setValue] = useState<String>();
  const [selectedIndex, setSelectedIndex] = useState<number | null>(null);
  const [isSelected, setIsSelected] = useState(false);
  const [isFirst, setIsFirst] = useState(true);
  const fadeIn = keyframes`
        from {
            opacity: 0;
            transform: translateY(100%); /* 初始位置在屏幕下方100% */
        }
        to {
            opacity: 1;
            transform: translateY(0); /* 结束位置在正常位置 */
        }
`;
  const CustomTitleCard: React.FC<CardProps> = ({ title, ...rest }) => {
    const [isHovered, setIsHovered] = useState(false);

    const handleMouseEnter = () => {
      setIsHovered(true);
    };

    const handleMouseLeave = () => {
      setIsHovered(false);
    };

    return (
      <Card
        style={{flex: 1,fontSize: '15px',marginBottom: 50, height: '100%', borderColor: isHovered ? '#fa541c' : ''}}
        {...rest}
        hoverable
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
        title={
          <p style={{fontWeight: 'bold', fontSize: '20px',marginTop: 20}}>
            {title}
          </p>
        }
      />
    );
  };
  const getLoginUser = async () => {
    try {
      const res = await getLoginUserUsingGet();
      sessionStorage.setItem('loginUser', JSON.stringify(res.data))
      setLoginUser(res.data);
    }catch (e) {
      history.push('/user/login')
    }
  }
  const checkPay =async (value:string,num:number)=>{
    try {
      const res = await isPayUsingPost({
        "out_trade_no": value,
        "vip":num==1?1:num==3?2:num==6?3:4,
      })
      if (res.data) {
        message.success("支付成功");
        getLoginUser();
      } else {
        message.error("支付失败");
      }
    }catch (e){
      console.log(e);
    }

  }
  const handlePay = async (value:number) => {
    message.loading("正在创建订单，请勿刷新界面");
    let currentDate = new Date();
    let currentMinute = currentDate.getMinutes();
    let currentSecond = currentDate.getSeconds();
    let orderTime = currentMinute + currentSecond;
    let out_trade_no = "vip"+'viptime'+value+`${loginUser?.id}`+orderTime;
    try {
      const res = await buyPointsUsingPost({
        "title":"会员购买",
        "goods_name":"e-api平台会员服务",
        "out_trade_no":out_trade_no,
        "total_amount":value==1?30:value==3?72:value==6?138:234,
      })
      if(res.data) {
        const html = res.data;

        Modal.confirm({
          cancelText: '未支付',
          content: '订单是否已经支付',
          centered: true,
          okText: '已支付',
          title: '支付确认',
          onOk: () => {
            message.loading('订单状态查询中，请勿刷新页面',1)
            checkPay(out_trade_no,value)
          },
          onCancel: () => {
            message.loading('订单状态查询中，请勿刷新页面',1)
            checkPay(out_trade_no,value)
          },
        })
        const newWindow = window.open('', '_blank', 'width=1500,height=1200');
        newWindow.document.write(html);
        newWindow.document.close();
        getLoginUser();
      }
      else
        message.error('购买失败');
    }catch (e) {
      console.log(e)
    }
  }
  const handleServiceActivation = (index: number) => {
    setSelectedIndex(index);
  };



  const onChange = (e: RadioChangeEvent) => {
    setValue(e.target.value)
  };
  useEffect(() => {
    setSelectedIndex(1);
    getLoginUser();
  }, []);
  const ManagerCard: React.FC<{
    title: string;
    index: number;
    desc: string;
    money: number;
    action: (index:number) => void;
    selectedIndex?: number;
  }> = ({ title, money, index, desc,action,selectedIndex }) => {
    const { useToken } = theme;
    const temp = money/index;
    const { token } = useToken();
    const isSelected = (selectedIndex === index);
    return (

      <Card
        onClick={()=>{
          action(index);
          setIsSelected(true);
        }}

        hoverable={true}
        style={{ width: "23.5%",
          height: '20%',
          borderRadius: '20px',
          fontSize: '16px',
          flex: 1,
          display: 'inline-block',
          marginRight: '1%',
          borderColor: isSelected ? token.colorPrimary : '#d9d9d9',
          transition: 'background-color 0.2s ease-in-out',
        }}
      >
        <div>
          <p
            style={{
              wordWrap: 'break-word',
              marginTop:  28,
              fontSize: '1.2vw',
              color: token.colorText,
              paddingBottom: 8,
              textAlign: 'center',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            {title}
          </p>
        </div>
        <div
          style={{
            fontSize: '15px',
            color: token.colorTextSecondary,
            textAlign: 'justify',
            lineHeight: '22px',
            marginBottom: 24,
            display:"flex",alignItems: 'center',justifyContent: 'center'
          }}
        >
          {desc}

        </div>
        <div style={{ display: 'flex', alignItems: 'center',justifyContent: 'center'}}>
          <p>{temp}元/月</p>
        </div>
      </Card>
    );
  };
  const fadeAndScaleIn = keyframes`
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
      `;
  return (
    <Layout style={{ animation: `${fadeAndScaleIn} 1s ease-in-out`}}>
      <Card title={<p style={{fontSize: '25px',fontWeight:'bold',marginTop:20}}>成为E-API平台会员吧</p>} style={{ width: '100%',height:'80%',marginTop:'20px' }}>
        <Content style={{ padding: '0 50px' }}>
          <Row gutter={[24, 24]}>
            <Col xs={24} sm={24} md={12} lg={12} xl={12}>
              {/* 左侧田字形排列的四个小卡片 */}
              <Row gutter={[8, 8]}>
                <Col span={12} >
                  <CustomTitleCard
                    hoverable='true'
                    title="调用积分特权"
                  >
                    <p>给您自由的调用体验。</p>
                    <p>立即获得100点调用积分，此后每个会员周我们都将赠送您30点积分。</p>
                  </CustomTitleCard>
                </Col>
                <Col span={12} >
                  <CustomTitleCard
                    hoverable='true'
                    title="专属节省计划"
                  >
                    <p>您的计费服务将加入节省计划。</p>
                    <p>在您的每个会员月，您都能享受到不定额的节省。</p>
                  </CustomTitleCard>
                </Col>
              </Row>
              <Row gutter={[8, 8]}>
                <Col span={12}>
                  <CustomTitleCard
                    title='私有化部署'
                  >
                    <p>平台可以为您提供私有化serverless部署。</p>
                    <p>为您提供全过程的接口对接支持。</p>
                  </CustomTitleCard>
                </Col>
                <Col span={12}>
                  <CustomTitleCard
                    hoverable='true'
                    title="7×24小时客服"
                  >
                    <p>平台专属全天候客服服务。</p>
                    <p>一对一解决您的烦恼。</p>
                  </CustomTitleCard>
                </Col>
              </Row>
            </Col>

            <Col span={12}>
              {/* 右侧大卡片 */}
              <Card
                title={<p style={{fontSize:'22px',fontWeight:'bold',marginTop:20,display:'flex'}}>会员服务开通账号：{loginUser?.userName==='null'?'野原新之助(默认)':loginUser?.userName}</p>}

                style={{ width: '105%',
                  flex: 1,
                  height: '100%',
                  marginBottom: 16 }}
              >
                <ManagerCard title='月度会员' index={1} desc='开通一个月会员' money={30} action={handleServiceActivation} selectedIndex={selectedIndex}></ManagerCard>
                <ManagerCard title='季度会员' index={3} desc='开通三个月会员' money={72} action={handleServiceActivation} selectedIndex={selectedIndex}></ManagerCard>
                <ManagerCard title='半年会员' index={6} desc='开通六个月会员' money={138} action={handleServiceActivation} selectedIndex={selectedIndex}></ManagerCard>
                <ManagerCard title='年度会员' index={12} desc='开通十二个月会员' money={234} action={handleServiceActivation} selectedIndex={selectedIndex}></ManagerCard>
                {/* 大卡片内容 */}
                <Button style={{
                  width: '100%',
                  height: '50px',
                  backgroundColor: '#1677ff',
                  color: theme.textColor,
                  borderRadius: '10px',
                  marginTop: '20px',
                  fontSize: '20px',
                  fontWeight: 'bold',
                  border: 'none',
                  cursor: 'pointer',
                }} type={'primary'} onClick={()=>{Modal.confirm({
                  content:`您即将开通${selectedIndex==1?'月':selectedIndex==3?'季':selectedIndex==6?'半年':'年'}度会员`,
                  title:'会员开通',
                  okText:'前往支付',
                  cancelText:'再想想',
                  onOk:()=>{
                    handlePay(selectedIndex)
                  },
                  duration:2,
                })
                }}>点击开通</Button>

              </Card>
            </Col>
          </Row>



          {/* 根据showQrCode状态决定是否显示二维码 */}

        </Content>
      </Card>
    </Layout>
  );
};

export default Vip;
